﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ArticleWeb
{
    public static class DatabaseExtension
    {
        public static int DeleteWhere(this DbContext db, string table, string where)
        {
            if (where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase))
            {
                return db.Database.ExecuteSqlCommand($"DELETE FROM {table} " + where);
            }
            return db.Database.ExecuteSqlCommand($"DELETE FROM {table} WHERE " + where);
        }
        public static int DeleteByIdList<T>(this DbContext db, string table, List<T> ids)
        {
            if (!ids.Any())
                return 0;
            return db.Database.ExecuteSqlCommand($"DELETE FROM {table} WHERE ID IN ('{string.Join("','", ids)}')");
        }

        public static int DeleteByFieldValues<T>(this DbContext db, string table, string fieldName, List<T> values)
        {
            if (!values.Any())
                return 0;
            return db.Database.ExecuteSqlCommand($"DELETE FROM {table} WHERE {fieldName} IN ('{string.Join("','", values)}')");
        }

        public static int DeleteByTwoFieldValues<T>(this DbContext db, string table, string fieldName, string fieldName2, List<T> values)
        {
            if (!values.Any())
                return 0;
            return db.Database.ExecuteSqlCommand($"DELETE FROM {table} WHERE {fieldName} IN ('{string.Join("','", values)}') OR {fieldName2} IN ('{string.Join("','", values)}')");
        }
    }
}